package cn.jb698.codec.msm.generator.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * @author LIU
 * @date 2023-05-24 17:07:29
 */
public class CodecGeneUtils {


	private static final Logger logger = LoggerFactory.getLogger(CodecGeneUtils.class) ;
	
	/**
     * 从 输入流 读出 字节数组
     * @param inputStream
     * @param bufferSize 缓冲大小,默认 4096 
     * @return
     * @throws IOException
     */
    public static byte[] readByteArrayFromInputStream(InputStream inputStream , Integer bufferSize ) throws IOException {
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		if(bufferSize == null ){
			bufferSize = 2048;
		}
		byte[] buffer = new byte[bufferSize];
		int bytesRead = inputStream.read(buffer);
		while (bytesRead != -1) {
			byteArrayOutputStream.write(buffer, 0, bytesRead);
			bytesRead = inputStream.read(buffer);
		}
		return byteArrayOutputStream.toByteArray();
      }


	/**
	 * 
	 * 转换字段名为属性名,如 col_name_abc -> colNameAbc, a_col_name -> colName , 
	 *  验证场景如下:
	 	Map<String,String> test_srcTgtMap = new HashMap<>(5);
		test_srcTgtMap.put("col_name_abc","colNameAbc");
		test_srcTgtMap.put("a_col_name","colName");
		test_srcTgtMap.put("col_nAme_aBc","colNameAbc");
		test_srcTgtMap.put("a_Col_Name","colName");
	 * @param colName
	 * @return
	 * 
	 */
	public static String parseColumnNameToPropName(String colName){
		String rtStr = colName ;
		StringBuffer buffer = new StringBuffer();
		
		// 将所有下划线后面的字符都转为大写,
		// 将所有下划线字符都替换为空字符
		String repStr = "_";
		
		Boolean isToUpperCase = false ;
		String regex = "[a-z,A-Z,0-9]";
		int indexStart = 0;
		if(repStr.equals(colName.substring(1, 2))){
			// 第二个字符如果为下划线,则将字段命名为从第3个字符开始.
			indexStart = 2 ;
		}
		for(int i=indexStart; i<colName.length(); i++ ){
			char tmpChar = colName.charAt(i);
			String tmpStr = String.valueOf(tmpChar);
			if(tmpStr.matches(regex)){
				if(isToUpperCase){
					tmpStr = tmpStr.toUpperCase();
					isToUpperCase = false ;
				}else{
					 tmpStr = tmpStr.toLowerCase();
				}
				buffer.append(tmpStr);
			}else{
				isToUpperCase = true ;
			}
		}
		rtStr = buffer.toString();
		return rtStr ;
	}

    /**
     * 根据根目录 及 类名 推断计算 目录,转换后的值以"/"结尾 
     * 例: /abc/com.cpnyxx.model/AbcdTableName --> /abc/com/cpnyxx/model/  ;   /abc/com.cpnyxx.model/subpath/ ->  /abc/com/cpnyxx/model/subpath/
     * @param rootDir 例: /src/main/java/
     * @param typePathStr 例: com.cpnyxx.bcrud.model.DtTableName
     * @return 
     */
	public static String parseAndCombineDirStr(String rootDir , String typePathStr ){
    	String rtStr ;
    	String tailDir = "";
    	if(!rootDir.endsWith("/")) {
    		rootDir += "/"; 
    	}
    	if(typePathStr != null ) {
    		typePathStr = typePathStr.trim();
    		if(!typePathStr.equals("")) {
    			tailDir = typePathStr.trim();
    		}
    	}
    	Integer lastPoint_index = typePathStr.lastIndexOf("."); // 
    	Integer lastPath_index = typePathStr.lastIndexOf("/"); // 
    	if(lastPoint_index > 0 || lastPath_index > 0 ){
    		String tmp_tailStr ;
    		if(lastPoint_index > 0 && lastPath_index > 0 ) {
    			if(lastPoint_index > lastPath_index) {
    				tmp_tailStr = typePathStr.substring(0,lastPoint_index);
    			}else {
    				tmp_tailStr = typePathStr.substring(0,lastPath_index);
    			}
    		}else if (lastPoint_index > 0 ) {
    			tmp_tailStr = typePathStr.substring(0,lastPoint_index);
    		}else {
    			tmp_tailStr = typePathStr ;
    		}
			tailDir = tmp_tailStr.replaceAll("\\.", "/");
    	}
    	if(tailDir.startsWith("/")) {
    		tailDir = tailDir.substring(1);
    	}
    	if(!tailDir.endsWith("/")) {
    		tailDir += "/";
    	}
    	rtStr = rootDir + tailDir;
    	File dirFile = new File(rtStr);
    	if(!dirFile.exists()){
    		dirFile.mkdirs();
    	}
    	logger.debug("计算后的输出目录:" + rtStr );
    	return rtStr ;
    }

    
    
    /**
     * label的分割符
     */
    static final String[] tableLabelNameSplitChars = {
        " ","~","`"
        ,"!","@","#","$","%","^","&","*","(",")","+","=","{","}","[","]","|","\"",":",";","\"","'","<",">",",",".","?","/"
        ,"！","@","#","￥","%","…","&","*","（","）","—","+","=","{","}","【","】","|","、","：","；","“","”","‘","’","《","》","，","。","？","、",
    };

    /**
     * 计算表级别备注名称
     * @param commentName
     * @return
     */
    public static String calcTableLabelName(String commentName) {
        if(Objects.isNull(commentName)) {
            return null;
        }
        String calcRtStr = commentName;
        calcRtStr = calcRtStr.trim();
        int findx = -1;
        int findxMin = -1;
        for (String tmpChar : tableLabelNameSplitChars) {
            findx = commentName.indexOf(tmpChar);
            if(findx > -1 && ( findxMin < 0 || ( findxMin >0 && findxMin > findx) ) ) {
                findxMin = findx;
            }
        }
        if(findxMin > 0 ) {
            calcRtStr = commentName.substring(0,findxMin);
        }
        return  calcRtStr;
    }

	
	/**
	 * label的分割符
	 */
    static final String[] columnLabelNameSplitChars = {
        " ","~","`"
        ,"!","@","#","$","%","^","&","*","(",")","_","-","+","=","{","}","[","]","|","\"",":",";","\"","'","<",">",",",".","?","/"
        ,"！","@","#","￥","%","…","&","*","（","）","—","+","-","=","{","}","【","】","|","、","：","；","“","”","‘","’","《","》","，","。","？","、",
    };
	 
	/**
	 * 计算字段Label名称
	 * @param commentName
	 * @return
	 */
	public static String calcColumnLabelName(String commentName) {
	    if(Objects.isNull(commentName)) {
	        return null;
	    }
	    String calcRtStr = commentName;
	    calcRtStr = calcRtStr.trim();
        int findx = -1;
        int findxMin = -1;
        for (String tmpChar : columnLabelNameSplitChars) {
            findx = commentName.indexOf(tmpChar);
            if(findx > -1 && ( findxMin < 0 || ( findxMin >0 && findxMin > findx) ) ) {
                findxMin = findx;
            }
        }
        if(findxMin > 0 ) {
            calcRtStr = commentName.substring(0,findxMin);
        }
	    return  calcRtStr;
	}
	
	
//	public static void main(String[] args) {
//
////	    {
////		String rootDir = "D:/workspace";
////		String javaType = "/com.cpnyxx.bcrud.model.DtTableName";
////		javaType = "/src/main/java/cn.jb698.ashengjun.bcrud/bcrud/ctrler/";
////		javaType = "/src/main/java/cn.jb698.ashengjun.bcrud/DtTableName.java/";
////		
////		System.err.println(parseAndCombineDirStr(rootDir, javaType)); 
////	    }
//	    
////	    {
////	       Map<String, String> testMap = new HashMap<>();
////	       testMap.put("Hello, world this is a test", "Hello");
////	       testMap.put("Hello  world this is a test", "Hello");
////	       testMap.put("字段中文名称(其他说明),<枚举>", "字段中文名称");
////	       testMap.put("字段名称XX", "字段名称XX");
////	       for(Entry<String, String> tmpEntry : testMap.entrySet() ) {
////	           String commentName = tmpEntry.getKey();
////	           String tmpTgtValue = tmpEntry.getValue();
////	           String calcRtStr = calcLabelName(commentName);
////	           boolean cmpRst = calcRtStr.equals(tmpTgtValue);
////	           System.err.println(commentName+"-->calcRst="+calcRtStr+ ""+"-->rst=" + cmpRst);
////	           Assert.assertTrue(cmpRst);
////	       }
////	    }
//		
//	}
	
}
